package com.example.questionnaire.controller;

import com.example.common.utils.Constant;
import com.example.common.utils.PageUtils;
import com.example.common.utils.R;
import com.example.questionnaire.dto.AnswerUserDto;
import com.example.questionnaire.dto.AnswererAddDto;
import com.example.questionnaire.entity.AnswererEntity;
import com.example.questionnaire.entity.QuestionnaireEntity;
import com.example.questionnaire.entity.ResultEntity;
import com.example.questionnaire.service.AnswererService;
import com.example.questionnaire.service.AnswererTeamService;
import com.example.questionnaire.service.UserAnswererService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * @author hsz
 * @email 1416446590@qq.com
 * @date 2022-10-29 11:20:57
 */
@Api("答者管理")
@CrossOrigin
@RestController
@RequestMapping("questionnaire/answerer")
public class AnswererController {
    @Autowired
    private AnswererService answererService;
    @Autowired
    private UserAnswererService userAnswererService;
    @Autowired
    private AnswererTeamService answererTeamService;
    /**
     * 列表
     * //3.分页展示答者信息
     * //4.支持模糊查询
     */

    @ApiOperation("答者列表，用户底下的答者列表，username(模糊查询)， userId，page，limit")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType = "int"),
//            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType = "int"),
//    })
    @GetMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = answererService.queryPage(params);
        return R.ok().put("data", page);
    }


    /**
     * 信息
     * //5.答者在无群组无答卷状态下支持修改、删除，系统记录曾经信息
     */
//    @ApiOperation("用户对答者信息进行管理,查看答者个人信息")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "id", value = "id", paramType = "query", required = true, dataType = "int")
//    })
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") Integer id) {
        AnswererEntity answerer = answererService.getById(id);
        return R.ok().put("data", answerer);
    }
    /**
     * 保存
     */
    @ApiOperation("答者自己注册,手机号注册，手机号、密码必填")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "answerer", value = "answerer", paramType = "save", required = true, dataType = "AnswererEntity")
    })
    @PostMapping("/save")
    public R save(@RequestBody AnswererEntity answerer) {
        int result = answererService.reg(answerer);
        if (result == 0){
            return R.error(1,"账号已存在");
        } else{
            return R.ok("注册成功");
        }
    }
    /**
     *用户添加答者的方法(和答者自己注册区分开)
     * @param answererAddDto
     * @return
     */
    @PostMapping("/add")
    public R addAnswererInfo(@RequestBody AnswererAddDto answererAddDto){
        int result=answererService.addAnswererInfo(answererAddDto);
        if (result == 0){
            return R.error(1,"账号已存在");
        }else if(result==2){
            return R.error(5,"手机号已存在");
        }
        else{
//            return R.ok("新建答者成功");
            userAnswererService.addUserAnswererInfo(answererAddDto);
            AnswererEntity answererEntity=answererService.queryAnswererByDto(answererAddDto);
            answererAddDto.setId(answererEntity.getId());
            answererService.addAnswererTeamInfo(answererAddDto);
            return R.ok("新建答者成功").put("data", answererEntity);
        }
    }
    /**
     * 修改
     */
    @PostMapping("/update")
    public R update(@RequestBody AnswererEntity answererEntity) {
        answererService.updateById(answererEntity);
//        answererService.modifyAnswererInfo(answererEntity);
        return R.ok().put("data",answererEntity);
    }

    /**
     * 删除
     */
    @ApiOperation("批量/单独删除该用户/群组下的  >=1 个答者，封装成AnswerUserDto")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "答者的id数组", paramType = "delete", required = true, dataType = "int[]"),
            @ApiImplicitParam(name = "userId", value = "关联这些答者的用户id", paramType = "delete", required = false, dataType = "int"),
            @ApiImplicitParam(name = "teamId", value = "关联这些答者的群组id", paramType = "delete", required = false, dataType = "int"),
    })
    @PostMapping("/delete")
    public R delete(@RequestBody AnswerUserDto answerUserDto) {
        if(answerUserDto.getTeamId()!=null){
            answererService.removeAnswererInTeam(answerUserDto.getIds(), answerUserDto.getTeamId());
        }else{
            answererService.removeAnswererInUser(answerUserDto.getIds(), answerUserDto.getUserId());
        }
        return R.ok();
    }
    @ApiOperation("批量导入答者(flag默认导入1，代表其有关联，无法修改)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "answerers", value = "answerers答者数组", required = true, dataType = "int[]"),
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "int")
    })
    @PostMapping("/savebatch")
    public R savebatch(@RequestBody AnswererEntity[] answerers, @RequestBody int userId) {
        answererService.saveAnswerersInUser(Arrays.asList(answerers), userId);
        return R.ok();
    }



    @ApiOperation("答者登录，暂定通过手机号telephone/用户名username，和密码登录")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "username", value = "用户名"),
            @ApiImplicitParam(name = "password", value = "密码")
    })
    @GetMapping("/login")
    public R login(@RequestParam(value = "username", required = false) String username, @RequestParam(value = "password", required = false) String password) {
        AnswererEntity answererEntity = answererService.login(username,password);
        if (answererEntity == null) {
            return R.error(2, "账号或密码错误");
        }
        return R.ok().put("data", answererEntity);
    }

    //    @ApiOperation("查询(分页、模糊查询)一下三个参数，都封装到Map类型的params；返回值R{code:0,data:答者数组,msg:\"\"}")
    @ApiOperation("答者问卷列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = "questionnaireName", value = "模糊查询questionnaireName答卷标题", paramType = "query", required = false, dataType = "String"),
            @ApiImplicitParam(name = "answererId", value = "答者answererId", paramType = "query", required = true, dataType = "int"),
    })
    @GetMapping("/resultlist")
    public R resultlist(@RequestParam Map<String, Object> params) {
        List<ResultEntity> resultEntities = answererService.queryResultList(params);
        return R.ok().put("data", resultEntities);
    }

    @ApiOperation("答者查看数据,传个questionnaireId,返回已经完成的答卷对象数组")
    @GetMapping("/analysis/{questionnaireId}")
    public R analysis(@PathVariable("questionnaireId") Integer questionnaireId) {
        List<ResultEntity> resultEntities = answererService.analysis(questionnaireId);
        return R.ok().put("data", resultEntities);
    }

    @ApiOperation("未关联答者列表teamId,userId,limit,page")
    @GetMapping("/relation")
    public R relation(@RequestParam Map<String, Object> params){
        PageUtils pageUtils=answererService.notRelation(params);
        return R.ok().put("data",pageUtils);
    }

    @ApiOperation("在未关联列表里关联,answererId,teamId")
    @PostMapping("/associate")
    public R associate(@RequestParam Map<String, Object> params){
        answererService.associate(params);
        return R.ok();
    }

    @ApiOperation("移除关联,answererId,teamId")
    @PostMapping("/removeAssociation")
    public R removeAssociation(@RequestParam Map<String, Object> params){
        answererService.removeAssociation(params);
        return R.ok();
    }

    @ApiOperation("查看某一群组下的答者,username(模糊查询),teamId，page，limit")
    @GetMapping("/teamanswerers")
    public R teamanswerers(@RequestParam Map<String, Object> params){
        PageUtils page = answererService.teamanswerers( params);
        return R.ok().put("data", page);

    }

    @ApiOperation("答者通过模糊搜索搜索问卷")
    @GetMapping("/searchByKeyWord")
    public R searchByKeyWord(@RequestParam(value = "answererId", required = false) Integer answererId, @RequestParam(value = "keyword", required = false) String keyword){
        List<Integer> QuestionnaireIdList = answererService.findQuestionnaireIdByAnswererId(answererId);
        List<QuestionnaireEntity> result = answererService.findQuestionnaireByKeyWord(QuestionnaireIdList, keyword);
        return R.ok().put("data",result);
    }
}

